<?php
function base64url_decode($data) { 
  return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT)); 
}
function base64url_encode($data) { 
  return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
} 

class Fpay {
	
  function __construct($partner,$rsakey){
    $this->partner = $partner;
	$this->rsakey = $rsakey;
  }
  
  function to_pay_by_user($money,$return_url,$notify_url,$type){
	  $rand =date("YmdHis").mt_rand(100000,999999);
	  $pu_key = openssl_pkey_get_public($this->rsakey);
	  $time = intval(time());
	  $data = json_encode(array(
              "ID"=>$this->partner,
              "Money"=>$money,
			  "PayID"=>$rand,
			  "type"=>$type,
			  "time"=>$time,
			  "return_url"=>$return_url,
			  "notify_url"=>$notify_url));
	  openssl_public_encrypt($data,$ensign,$pu_key);//公钥加密
	  header('Location: http://openapi.mcpe.cc/gateway.do?id='.$this->partner.'&money='.$money.'&payid='.$rand.'&sign='.base64url_encode($ensign).'&return_url='.$return_url.'&notify_url='.$notify_url.'&type='.$type.'&time='.$time); 
  }
  function check_return_data($sign,$money,$payid,$id,$fpayid){
	  $pu_key = openssl_pkey_get_public($this->rsakey);
	  $decode = base64url_decode($sign);
	  openssl_public_decrypt($decode,$design,$pu_key);
	  $data = json_encode(array("id"=>$id,"money"=>$money,"payid"=>$payid,"fpayid"=>$fpayid));
	  if($design===$data){
		return true;
	  }else{
		return false;
	  }
  }
  function get_user_pay_status($shno){
	  $encode = $shno.'|'.$this->partner;
	  $pu_key = openssl_pkey_get_public($this->rsakey);
      openssl_public_encrypt($encode,$ensign,$pu_key);
	  $status = file_get_contents('https://pay.mcpe.cc/Gateway.do?partner='.$this->partner.'&sign='.base64url_encode($ensign).'&type=get_user_pay_status');
	  if($status==='ok'){
	    return true;
	  }else{
		return false;
	  }
  }
}
